<script setup>
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { updatePassword } from '@/api/student'
import { useRouter } from 'vue-router'

const form = reactive({
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
})

const loading = ref(false)
const router = useRouter()

const submit = () => {
    if (!form.oldPassword) {
        ElMessage.error('请输入原密码')
        return
    }
    if (!form.newPassword) {
        ElMessage.error('请输入新密码')
        return
    }
    if (form.newPassword !== form.confirmPassword) {
        ElMessage.error('两次输入的新密码不一致')
        return
    }

    loading.value = true
    updatePassword({
        password: form.oldPassword,
        newPassword: form.newPassword
    }).then((res) => {
        ElMessage.success('密码修改成功，请重新登录')

        // 清除本地存储的令牌和学生信息
        localStorage.removeItem('token')
        localStorage.removeItem('studentInfo')

        // 显示确认对话框
        ElMessageBox.confirm(
            '密码修改成功！为了安全起见，请重新登录。',
            '提示',
            {
                confirmButtonText: '重新登录',
                cancelButtonText: '取消',
                type: 'success',
                showCancelButton: false
            }
        ).then(() => {
            // 跳转到登录页面
            router.push('/login')
        })

        // 清空表单
        form.oldPassword = ''
        form.newPassword = ''
        form.confirmPassword = ''
    }).catch((error) => {
        ElMessage.error(error?.msg || error?.message || '修改失败')
    }).finally(() => {
        loading.value = false
    })
}

</script>

<template>
    <el-card>
        <template #header>
            <div class="header">修改密码</div>
        </template>

        <el-form label-width="100px" :model="form" style="max-width: 460px;">
            <el-form-item label="原密码">
                <el-input v-model="form.oldPassword" type="password" show-password />
            </el-form-item>
            <el-form-item label="新密码">
                <el-input v-model="form.newPassword" type="password" show-password />
            </el-form-item>
            <el-form-item label="确认新密码">
                <el-input v-model="form.confirmPassword" type="password" show-password />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" :loading="loading" @click="submit">提交</el-button>
            </el-form-item>
        </el-form>
    </el-card>

</template>

<style scoped lang="scss"></style>
